package exchange;

import main.QConomy;

import org.bukkit.conversations.ConversationAbandonedEvent;
import org.bukkit.conversations.ConversationAbandonedListener;
import org.bukkit.conversations.ConversationFactory;
import org.bukkit.entity.Player;

public class Exchange implements ConversationAbandonedListener {
	private final ConversationFactory factory;
	private ItemList items;
	private final ExchangeLoader exchangeLoader;

	public Exchange(QConomy plugin) {
		factory = new ConversationFactory(plugin)
		.withModality(false)
		.withEscapeSequence("/exit")
		.withTimeout(30)
		.addConversationAbandonedListener(this);
		exchangeLoader = new ExchangeLoader();
		items = exchangeLoader.loadItems();
	}
	
	public boolean addItem(Item item) {
		return items.addItem(item);
	}
	
	public boolean removeItem(Item item) {
		return items.removeItem(item);
	}
	
	public void start(Player player) {
		factory.withFirstPrompt(new ExchangePrompt(items));
		factory.buildConversation(player).begin();
	}
	
	@Override
	public void conversationAbandoned(ConversationAbandonedEvent event) {
		if (event.getContext().getSessionData("reset") != null) {
			Item item = (Item) event.getContext().getSessionData("item");
			int quantity = (int) event.getContext().getSessionData("reset");
			item.increaseQuantity(quantity);
		}
		event.getContext().getForWhom().sendRawMessage("Exited out of the Exchange");
	}
}